<template>
  <div class="page-container">
    <!-- 筛选表单 -->
    <div class="filter-section">
      <el-form :model="filters" inline class="filter-form">
        <el-form-item label="邮箱">
          <el-input v-model="filters.email" placeholder="请输入邮箱" clearable class="filter-input" />
        </el-form-item>
        <el-form-item label="用户名">
          <el-input v-model="filters.username" placeholder="请输入用户名" clearable class="filter-input" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchAdmins">筛选</el-button>
          <el-button @click="resetFilters">重置</el-button>
        </el-form-item>
        <el-button type="primary" icon="Plus" @click="dialogVisible = true">新建管理员</el-button>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <el-table 
        v-loading="loading"
        :data="admins"
        style="width: 100%"
        stripe
        class="data-table"
      >
        <el-table-column prop="username" label="用户名" min-width="120" align="center" />
        <el-table-column prop="email" label="邮箱" min-width="180" align="center" />
        <el-table-column prop="roleId" label="角色" width="120" align="center">
          <template #default="{row}">
            <el-tag :type="row.roleId === 1 ? 'success' : 'info'">
              {{ row.roleId === 1 ? '系统管理员' : '未知' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="180" align="center">
          <template #default="{row}">
            {{ new Date(row.createTime).toLocaleDateString() }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right" align="center">
          <template #default="{row}">
            <el-popconfirm
              title="确定删除该管理员？"
              @confirm="handleDeleteAdmin(row.id)"  <!-- 修改为使用用户ID -->
            >
              <template #reference>
                <el-button type="danger" size="small" plain>删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 新增弹窗 -->
    <el-dialog 
      v-model="dialogVisible" 
      title="新建管理员" 
      width="500px"
      :close-on-click-modal="false"
      custom-class="custom-dialog"
    >
      <el-form :model="form" label-width="80px" label-position="left" class="dialog-form">
        <el-form-item label="用户名" required>
          <el-input v-model="form.username" placeholder="2-16位字符" class="dialog-input" />
        </el-form-item>
        <el-form-item label="邮箱" required>
          <el-input v-model="form.email" placeholder="有效邮箱地址" class="dialog-input" />
        </el-form-item>
        <el-form-item label="密码" required>
          <el-input v-model="form.password" type="password" placeholder="6-20位字符" class="dialog-input" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAddAdmin">立即创建</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { accountList, accountAdd, accountDel } from '@/api/account';

// 表格数据和加载状态
const admins = ref([]);
const loading = ref(false);

// 新增对话框状态和表单数据
const dialogVisible = ref(false);
const form = ref({
  username: '',
  email: '',
  password: '',
  roleId: 2,
  houseId: 1,
  account: 0
});

// 筛选条件
const filters = ref({
  email: '',
  username: ''
});

// 获取管理员列表
const fetchAdmins = async () => {
  try {
    loading.value = true;
    const processedFilters = {
      email: filters.value.email || null,
      username: filters.value.username || null
    };
    const response = await accountList(processedFilters);
    if (response.data.code === 200) {
      admins.value = response.data.data || [];
    } else {
      ElMessage.error('获取失败:' + response.data.msg);
    }
  } catch (error) {
    ElMessage.error('请求失败:' + error.message);
  } finally {
    loading.value = false;
  }
};

// 提交新增管理员
const handleAddAdmin = async () => {
  try {
    if (!form.value.username.trim()) {
      ElMessage.warning('请输入用户名');
      return;
    }
    if (!/^\w+@\w+\.\w+$/.test(form.value.email)) {
      ElMessage.warning('请输入有效邮箱');
      return;
    }
    if (form.value.password.length < 6 || form.value.password.length > 20) {
      ElMessage.warning('密码长度必须在6-20位之间');
      return;
    }

    const formData = {
      username: form.value.username.trim(),
      email: form.value.email,
      password: form.value.password,
      roleId: form.value.roleId,
      houseId: form.value.houseId,
      account: form.value.account
    };

    const response = await accountAdd(formData);
    if (response.data.code === 200) {
      ElMessage.success('新增成功');
      dialogVisible.value = false;
      form.value = { username: '', email: '', password: '', roleId: 2, houseId: 1, account: 0 };
      fetchAdmins();
    } else {
      ElMessage.error('新增失败:' + response.data.msg);
    }
  } catch (error) {
    ElMessage.error('新增失败:' + error.message);
  }
};

// 删除管理员
const handleDeleteAdmin = async (id) => {  // 修改为接收用户ID
  try {
    const response = await accountDel({ id });  // 修改为传递用户ID
    if (response.data.code === 200) {
      ElMessage.success('删除成功');
      fetchAdmins();
    } else {
      ElMessage.error('删除失败:' + response.data.msg);
    }
  } catch (error) {
    ElMessage.error('删除失败');
  }
};

// 重置筛选条件
const resetFilters = () => {
  filters.value = { email: '', username: '' };
  fetchAdmins();
};

// 页面加载时获取管理员列表
onMounted(() => {
  fetchAdmins();
});
</script>

<style scoped>
.page-container {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 40px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 0 10px;
}

.filter-section {
  margin-bottom: 20px;
  padding: 0 10px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.filter-input {
  width: 200px;
}

.table-section {
  padding: 0 10px;
}

.data-table {
  width: 100%;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  overflow: hidden;
}

.custom-dialog {
  border-radius: 8px;
}

.dialog-form {
  width: 100%;
}

.dialog-input {
  width: 100%;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

:deep(.el-table__header-wrapper) {
  margin-bottom: 10px;
}

:deep(.el-table__body-wrapper) {
  overflow-y: auto;
  height: 500px;
}

:deep(.el-table__cell) {
  padding: 8px 10px;
}

:deep(.el-tag) {
  margin: 2px;
}

:deep(.el-button) {
  margin-right: 5px;
}

:deep(.el-popconfirm) {
  display: inline-block;
}
</style>